/**
 * Session Storage 封装
 * 格式：mall: [
 *              {"user":{name: "zihou", tel: "15168841751"}},
 *              {"test":{"a": 2}},
 *              ...
 *            ]
 **/
const STORAGE_KEY = 'mall';
export default {
    /**
     * 存储 键：值
     * module_name: 在某个模块下添加值 如 user下添加username
     */
    setItem(key, value, module_name) {
        if (module_name) {
            let val = this.getItem(module_name)
            val[key] = value
            //递归调用
            this.setItem(module_name, val)
        } else {
            //获取所有缓存
            let val = this.getStorage()
            val[key] = value
            window.localStorage.setItem(STORAGE_KEY, JSON.stringify(val)) //json对象转换成字符串
        }
    },
    /**
     * 获取值
     * module_name: 获取某一个模块下面的属性 如 user下面的username
     */
    getItem(key, module_name) {
        if (module_name) {
            let val = this.getItem(module_name)
            if (val) {
                return val[key]
            }
        }
        return this.getStorage()[key]
    },
    //获取整个缓存数据
    getStorage() {
        return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}')
    },
    /**
     * 删除 键：值
     * module_name: 删除某个模块下的值 如 user下添加username
     */
    clear(key, module_name) {
        let val = this.getStorage()
        if (module_name) {
            delete val[module_name][key]
        } else {
            delete val[key]
        }
        window.localStorage.setItem(STORAGE_KEY, JSON.stringify(val))
    }
}